package com.spring;

import com.spring.annotation.*;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AnnotationConfigApplicationContext {

    private Class configClass;

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorsList = new ArrayList<>();

    public AnnotationConfigApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 扫描
        scan(configClass);

        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equalsIgnoreCase("singleton") && !beanDefinition.isLazy()) {
                createBean(beanName, beanDefinition);
            }
        }
    }

    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();

        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();

            // Autowired 处理
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }

            // 初始化前 @PostConstruct
            // 初始化 InitializingBean
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            // 初始化后 BeanPostProcessor
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                // 如果 有AOP需求 这里会返回代理对象
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }
            // AOP 基于BeanPostProcessor实现的
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        return instance;
    }


    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

        if (beanDefinition == null) {
            throw new NullPointerException();
        }

        if ("singleton".equalsIgnoreCase(beanDefinition.getScope())) {
            // 单例
            Object result = singletonObjects.get(beanName);
            if (result == null) {
                result = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, result);
            }
            return result;
        } else {
            return createBean(beanName, beanDefinition);
        }
    }

    // 扫描
    private void scan(Class configClass) {
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            String path = componentScanAnnotation.value();

            // 查找编译之后的 classes 目录，加载类
            path = path.replace(".", "/");
            ClassLoader classLoader = AnnotationConfigApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);

            // 获取到目录
            File file = new File(resource.getFile());
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    String absolutePath = f.getAbsolutePath();
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    absolutePath = absolutePath.replace("/", ".");

                    try {
                        Class<?> clazz = classLoader.loadClass(absolutePath);

                        // isAssignableFrom() 是 Java 反射 API 中 Class 类的一个重要方法，用于判断一个类或接口是否可以赋值给另一个类或接口
                        if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                            BeanPostProcessor instance = (BeanPostProcessor) clazz.getConstructor().newInstance();
                            beanPostProcessorsList.add(instance);
                        }

                        if (clazz.isAnnotationPresent(Component.class)) {
                            BeanDefinition beanDefinition = new BeanDefinition();

                            beanDefinition.setType(clazz);
                            beanDefinition.setLazy(clazz.isAnnotationPresent(Lazy.class));

                            // Bean
                            // 判断单例还是原型
                            if (clazz.isAnnotationPresent(Scope.class) && clazz.getAnnotation(Scope.class).value().equalsIgnoreCase("prototype")) {
                                beanDefinition.setScope("prototype");
                            } else {
                                // Scope没有配置，默认单例模式
                                beanDefinition.setScope("singleton");
                            }

                            // spring 对没有配置名称的beanName有默认名称的处理
                            String beanName = clazz.getAnnotation(Component.class).value();
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

        }
    }
}
